package com.wowoai.user.controller;

import com.wowoai.common.annotation.NotNeedAuth;
import com.wowoai.common.factoy.JWTCreateFactory;
import com.wowoai.common.response.ResponseVO;
import com.wowoai.common.userInfo.CurrentUserInfo;
import com.wowoai.common.userInfo.UserInfo;
import com.wowoai.user.controller.req.UserInfoReq;
import com.wowoai.user.controller.req.UserReq;
import com.wowoai.user.controller.vo.UserVO;
import com.wowoai.user.convert.UserConvert;
import com.wowoai.user.enums.UserScoreOptionTypeEnum;
import com.wowoai.user.service.UserServiceI;
import com.wowoai.user.service.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * 用户controller
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserServiceI userServiceI;

    public UserController(UserServiceI userServiceI){
        Assert.notNull(userServiceI,"userServiceI 不能为空");
        this.userServiceI = userServiceI;
    }

    @GetMapping("/getUserByPhoneNumber")
    public ResponseVO<UserVO> getUserByPhoneNumber() {
        UserDTO userDTO = userServiceI.getUserByPhoneNumber(CurrentUserInfo.getUserInfo().getPhoneNumber());
        UserVO userVO = UserConvert.INS.dto2VO(userDTO);
        if (Objects.isNull(userVO.getAdCount())){
            userVO.setAdCount(0);
        }
        return ResponseVO.success(userVO);
    }

    @PostMapping("/login")
    @NotNeedAuth
    public ResponseVO<UserVO> login(@RequestBody @Valid UserReq req, HttpServletResponse response) {
        UserDTO userDTO = userServiceI.loginAndRegister(req);//去校验和登录
        if (Objects.nonNull(userDTO)) {
            //如果登录成功则去创建token
            this.createToken(response, userDTO);
        }
        return ResponseVO.success(UserConvert.INS.dto2VO(userDTO));
    }

    @GetMapping("/updateSubtractScore")
    public ResponseVO<Void> updateSubtractScore(@RequestParam("subtractScore") Integer subtractScore,@RequestParam(value = "optionType",required = false) String optionType){
        log.info("扣减积分");
        UserInfo userInfo = CurrentUserInfo.getUserInfo();
        UserDTO userDTO = userServiceI.getUserByPhoneNumber(userInfo.getPhoneNumber());
        UserScoreOptionTypeEnum optionTypeEnum = UserScoreOptionTypeEnum.AI_CHAT;//默认ai对话
        if (Objects.equals(optionType,UserScoreOptionTypeEnum.DOWNLOAD_WALLPAPER.getCode().toString())){
            optionTypeEnum = UserScoreOptionTypeEnum.DOWNLOAD_WALLPAPER;
        }

        userServiceI.updateScore(userDTO, subtractScore,optionTypeEnum,"-" + subtractScore);
        //扣减积分
        return ResponseVO.success(null);
    }

    /**
     * 提示成功之后更新值，不在提示
     */
    @GetMapping("/tipsSuccess")
    public ResponseVO<Void> tipsSuccess(){
        userServiceI.tipsSuccess(CurrentUserInfo.getUserInfo().getPhoneNumber());
        return ResponseVO.success(null);
    }
    /**
     * 获取是否响应提示
     * @return true -> 需要提示 ;flase -> 不需要
     */
    @GetMapping("/getTipsStatus")
    public ResponseVO<Boolean> getTipsStatus() {
        String phoneNumber = CurrentUserInfo.getUserInfo().getPhoneNumber();
        UserDTO userByPhoneNumber = userServiceI.getUserByPhoneNumber(phoneNumber);
        return ResponseVO.success(userByPhoneNumber.getScoreTagFlag());
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/updateAvatar")
    public ResponseVO<UserDTO> updateAvatar(MultipartFile avatar) {
        UserInfo userInfo = CurrentUserInfo.getUserInfo();
        UserReq userReq = new UserReq();
        userReq.setAvatar(avatar);
        UserDTO userDTO = userServiceI.updateUserInfo(userReq, userInfo);
        return ResponseVO.success(userDTO);
    }

    @PostMapping("/updateUserInfo")
    public ResponseVO<UserDTO> updateUserInfo(@RequestBody UserInfoReq userInfoReq) {
        UserInfo userInfo = CurrentUserInfo.getUserInfo();
        UserReq userReq = new UserReq();
        userReq.setNickName(userInfoReq.getNickName());
        UserDTO userDTO = userServiceI.updateUserInfo(userReq, userInfo);
        return ResponseVO.success(userDTO);
    }

    /**
     *  新增积分
     * @param score  临时积分
     * @param permanentScore 永久积分
     * @return 成功或者失败
     */
    @GetMapping("/addScoreForAd")
    public ResponseVO<Boolean> addScore(@RequestParam(value = "score",required = false) Integer score,@RequestParam(value = "permanentScore",required = false) Integer permanentScore){
        log.info("新增积分 ={}",score);
        Boolean result = userServiceI.addScore(CurrentUserInfo.getUserInfo(),score, permanentScore, UserScoreOptionTypeEnum.AD);
        return ResponseVO.success(result);
    }

    /**
     * 创建token
     *
     */
    private void createToken(HttpServletResponse response, UserDTO userDTO) {
        //生成token
        try {
            String token = JWTCreateFactory.createToken(userDTO.getPhoneNumber());
            response.setHeader(JWTCreateFactory.USER_LOGIN_TOKEN, token);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
